package com.zhengxyou.demoscrolltab

import android.animation.ObjectAnimator
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.animation.doOnEnd
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.zhengxyou.demoscrolltab.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private var topHeight: Int = 0
    private var searchAreaHeight: Int = 0


    private val minMove: Int = 200//最小距离

    private var scroll: Int = 0//第一页向上滚动的距离
//    private var topLocationY: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        if (binding.vpContent.currentItem == 0) {
            binding.llTop.setBackgroundColor(Color.TRANSPARENT)
            binding.tabLayout.setBackgroundColor(Color.TRANSPARENT)
        }

        binding.llTop.post {
            topHeight = binding.llTop.height
        }
        binding.llTopInput.post {
            searchAreaHeight = binding.llTopInput.height
        }

        val fragments: MutableList<Fragment> = ArrayList()
        val tab1 = binding.tabLayout.newTab()
        tab1.apply {
            text = "tab 图片"
        }
        fragments.add(ImageViewFragment.newInstance())
        binding.tabLayout.addTab(tab1)

        for (i in 1..5) {
            val tab = binding.tabLayout.newTab()
            tab.apply {
                text = "tab $i"
            }
            fragments.add(TextFragment.newInstance(tab.text.toString()))
            binding.tabLayout.addTab(tab)
        }

        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
//                Toast.makeText(this@MainActivity, "Selected:${tab?.text}", Toast.LENGTH_SHORT)
//                    .show()
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
//                Toast.makeText(
//                    this@MainActivity,
//                    "Unselected:${tab?.text}",
//                    Toast.LENGTH_SHORT
//                ).show()
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
                Toast.makeText(
                    this@MainActivity,
                    "Reselected:${tab?.text}",
                    Toast.LENGTH_SHORT
                ).show()
            }

        })

        binding.vpContent.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return fragments.size
            }

            override fun createFragment(position: Int): Fragment {
                return fragments[position]
            }
        }
        binding.vpContent.registerOnPageChangeCallback(changeCallback)

        TabLayoutMediator(binding.tabLayout, binding.vpContent) { tab, position ->
            tab.text = "tabM $position "
        }.attach()
    }

    private var isLeft = false
    private val changeCallback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            Log.d("TAG", "$position");
            showInput()
        }

        override fun onPageScrollStateChanged(state: Int) {
            super.onPageScrollStateChanged(state)
            if (binding.vpContent.currentItem == 0 && isLeft) {
                if (scroll < topHeight) {
                    binding.llTop.setBackgroundColor(Color.TRANSPARENT)
                    binding.tabLayout.setBackgroundColor(Color.TRANSPARENT)
                }
            } else if (binding.vpContent.currentItem == 1 && !isLeft) {
                binding.llTop.setBackgroundColor(Color.WHITE)
                binding.tabLayout.setBackgroundColor(Color.WHITE)
            }
        }

        var lastPositionOffset = 0F
        override fun onPageScrolled(
            position: Int,//当前页面
            positionOffset: Float,//左滑的百分比是从1~0，右滑的参数是0~1
            positionOffsetPixels: Int
        ) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            Log.d("TAG", "onPageScrolled:$position,$positionOffset,$lastPositionOffset")
            if (positionOffset > 0) {
                if (positionOffset > lastPositionOffset) {        // 用户正在向右滑动
                    Log.d("TAG", "用户正在向右滑动")
                    isLeft = false
                } else if (positionOffset < lastPositionOffset) {        // 用户正在向左滑动
                    Log.d("TAG", "用户正在向左滑动")
                    isLeft = true
                    if (position == 0 && scroll < topHeight) {
                        binding.llTop.setBackgroundColor(Color.TRANSPARENT)
                        binding.tabLayout.setBackgroundColor(Color.TRANSPARENT)
                    }
                }
            }

            lastPositionOffset = positionOffset;
        }
    }

    fun getTopHeight() = topHeight
    override fun onDestroy() {
        super.onDestroy()
        binding.vpContent.unregisterOnPageChangeCallback(changeCallback)
    }

    /**
     * @param scrollY 滚动顶部的位置， recyclerview.scrollY
     * @param dy 滑动的距离 大于0上划
     */
    fun scrollCallback(scrollY: Int, dy: Int) {
        if (binding.vpContent.currentItem == 0) {
            scroll = scrollY
            //往上拉
            if (dy > 0) {
                if (scrollY < topHeight) {
                    binding.llTop.setBackgroundColor(Color.TRANSPARENT)
                    binding.tabLayout.setBackgroundColor(Color.TRANSPARENT)
                } else if (scrollY > topHeight && scrollY < (topHeight + searchAreaHeight)) {
                    binding.llTop.setBackgroundColor(Color.WHITE)
                    binding.tabLayout.setBackgroundColor(Color.WHITE)
                } else if (scrollY > (topHeight + searchAreaHeight)) {//隐藏搜索区域
                    hideInput()
                }
            } else {//往下拉
                if (scrollY < topHeight) {
                    binding.llTop.setBackgroundColor(Color.TRANSPARENT)
                    binding.tabLayout.setBackgroundColor(Color.TRANSPARENT)
                } else if (scrollY > topHeight && scrollY < (topHeight + searchAreaHeight)) {
                    binding.llTop.setBackgroundColor(Color.WHITE)
                    binding.tabLayout.setBackgroundColor(Color.WHITE)
                } else if (scrollY > (topHeight + searchAreaHeight)) {//显示搜索区域
                    showInput()
                }
            }

        } else {
            //往上拉
            if (dy > 0) {
                if (scrollY > topHeight) {
                    hideInput()
                }
            } else {//往下拉
                showInput()
            }
        }
    }

    var translateAnimation: ObjectAnimator? = null
    private fun showInput() {
//        translateAnimation?.cancel()
        if (translateAnimation == null) {
            translateAnimation = ObjectAnimator.ofFloat(
                binding.llTop,
                "y",
                binding.llTop.y,
                0F
            )
            translateAnimation?.apply {
                duration = 200
//            interpolator = AccelerateInterpolator()
                doOnEnd {
                    translateAnimation = null
                }
                start()
            }
        }


    }

    private fun hideInput() {
//        translateAnimation?.cancel()
        if (translateAnimation == null) {
            translateAnimation = ObjectAnimator.ofFloat(
                binding.llTop,
                "y",
                binding.llTop.y,
                -searchAreaHeight.toFloat()
            )
            translateAnimation?.apply {
                duration = 200
//            interpolator = AccelerateInterpolator()
                doOnEnd {
                    translateAnimation = null
                }
                start()
            }
        }

    }
}